//全部商机

const router = require('koa-router')()
const { guanhuai } = require('../model')

// 添加数据
router.post('/guanhuai/add', async (ctx, next) => {
  const {name,customerName,state,establishTime,nums,updateTime,} = ctx.request.body
  const res = await guanhuai.create({name,customerName,state,establishTime,nums,updateTime})
  if (res) {
    ctx.body = {
      code: 200,
      msg: '添加成功',
      name,customerName,state,establishTime,nums,updateTime
    }
  }
})

// 获取全部数据
router.post('/guanhuai/getAll', async (ctx, next) => {
  const res = await guanhuai.find();
  console.log(res);
  if (res) {
    ctx.body = {
      code: 200,
      msg: '获取全部数据成功',
      data: res
    }
  }
})

// 修改数据
router.post('/guanhuai/update', async (ctx, next) => {
  const {ids,name,customerName,state,establishTime,nums,updateTime  } = ctx.request.body
  let res = await guanhuai.updateOne(
    { _id: ids },
    {name,customerName,state,establishTime,nums,updateTime} 
  )
  if (res) {
    ctx.body = {
      code: 200,
      msg: '修改成功',
      data: res,
    }
  }
})

//删除
router.post('/guanhuai/del', async (ctx, next) =>{
  const { id } = ctx.request.body
  const res = await guanhuai.deleteOne({ _id: id })

  if (res) {
      ctx.body = {
          code: 200,
          msg: '删除成功',
          data: res
      }
  }
})

// 多条件搜索
router.post('/guanhuai/search', async (ctx, next) =>{
  const { names, time, state } = ctx.request.body
  let res=await guanhuai.find({$and:[
      {names:new RegExp(names)},
      {time:new RegExp(time)},
      {state:new RegExp(state)},
  ]})
  
  if(res){
      ctx.body={
          code:200,
          msg:'搜索成功',
          data:res
      }
  }
})

module.exports = router